#include "Enviroment.h"
#include "Utilities.h"
#include <cstdlib>
#include <iostream>

Enviroment :: Enviroment(Database * db)
: db(db)
{
	scanPaths();
}

std::string Enviroment :: getVar(std::string var)
{
	return getenv(var.c_str());
}

void Enviroment :: getVar(std::string var,std::string val)
{
	setenv(var.c_str(),val.c_str(),1);
}

void Enviroment :: scanPaths()
{
	SVector paths = getPaths();
	std::string tmp,tstamp;
	int scanned = 0;
	for(SVector::iterator path = paths.begin() ; path != paths.end() ; path++)
	{
		tstamp = getFileModTime(*path);
		db->execUnarryStrStatement("select last_scan from PathTable where pid==(select uid from StrTab where value==\""+*path+"\");",tmp);
		if( tstamp != tmp)
		{	//Either modified since last scan or first encounter!
			db->execStatement("insert or replace into PathTable (pid,last_scan) values ("+db->addString(*path)+",\""+tstamp+"\")");
			scanned += scanPath(*path,0);
		}
	}
	if(scanned)
		db->vacuum();
}
int Enviroment :: scanPath(std::string path,int lvl)
{
	std::vector<std::string> files = getPathFiles(path);
	if(files.size() == 0)
		return 0;
	if(!lvl)
		db->execStatement("begin transaction;");

	for(SVector::iterator itr = files.begin() ; itr != files.end() ; itr++)
	{
		if(checkFileIsExec(path,*itr))
		{
			db->execStatement("insert or ignore into ExecList (name,path) values ("
				+db->addString(*itr)+","
				+db->addString(path)+");");
		}
		else
		{
			scanPath(path+"/"+*itr,lvl+1);
		}
	}
	if(!lvl)
		db->execStatement("commit transaction;");
	return 1;
}
Enviroment :: ~Enviroment()
{

}
